//
//  WDRewardedVideoManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/6/1.
//

#import "WDRewardedVideoManager.h"
#import "WDAdStatusManager.h"
#import "WDCallBackManager.h"
#import "WDAdStatusManager.h"
#import "WDJsonManager.h"

@import Adjust;
#import <AppLovinSDK/AppLovinSDK.h>

@interface WDRewardedVideoManager ()<MARewardedAdDelegate,MAAdRevenueDelegate>
@property (nonatomic, assign)BOOL receiveRewardForPlacement;
@property (nonatomic, assign) BOOL hasShowAd;
@property (nonatomic, strong) MARewardedAd *rewardedAd;
@property (nonatomic, assign) NSInteger retryAttempt;
@end
@implementation WDRewardedVideoManager
static WDRewardedVideoManager *_rewardedVideo = nil;
+ (instancetype)shareRewardedVideoManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _rewardedVideo = [[self alloc] init];
        
    });
    return _rewardedVideo;
}

- (void)irDelegate
{
    self.rewardedAd = [MARewardedAd sharedWithAdUnitIdentifier: [WDJsonManager maxRewardForSDKConfigFile]];
    
    self.rewardedAd.delegate = self;
    self.rewardedAd.revenueDelegate = self;
    
    // Load the first ad
    [self.rewardedAd loadAd];
}

- (void)showIrSourceRV
{
    [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"WDOrientation"];
    self.receiveRewardForPlacement = NO;
    
    
    if ( [self.rewardedAd isReady] )
    {
        [self.rewardedAd showAd];
       [[WDAdStatusManager shareStatusManager] adShowWithEventName:RV_EVENT_NAME];

    }else{
        
        if ([WDCallBack shareCallBack].onRewardVideoHas)
        {
            [WDCallBack shareCallBack].onRewardVideoHas(NO);
        }
        self.hasShowAd = YES;
        [self loadRV];
    }
    

    
}

- (void)loadRV
{
    
    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.rewardedAd loadAd];
    });
}



#pragma mark - MAAdDelegate Protocol

/**
 * 广告加载成功回调
 *
 * @param ad 加载成功的广告对象
 */
- (void)didLoadAd:(MAAd *)ad
{
    [[WDAdStatusManager shareStatusManager] adLoadFillSuccessWithEventName:RV_EVENT_NAME];
    if (self.rewardedVideoDidLoadCallBackBlcok)
    {
        self.rewardedVideoDidLoadCallBackBlcok(YES);
    }
    if (self.hasShowAd)
    {
        self.hasShowAd = NO;
        [self showIrSourceRV];
    }
}

/**
 * 广告加载失败回调
 *
 * @param adUnitIdentifier 广告单元标识符
 * @param error 加载失败错误信息
 */
- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error
{
    // Rewarded ad failed to load. We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds).
    self.retryAttempt++;
    NSInteger delaySec = pow(2, MIN(6, self.retryAttempt));
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self.rewardedAd loadAd];
    });
}

/**
 * 广告展示回调
 *
 * @param ad 展示的广告对象
 */
- (void)didDisplayAd:(MAAd *)ad
{
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Show adSpace:reward message:@""];
}

/**
 * 广告点击回调
 *
 * @param ad 被点击的广告对象
 */
- (void)didClickAd:(MAAd *)ad
{
    NSLog(@"------didClickAd---%@",ad.description);
    [[WDAdStatusManager shareStatusManager] adClickWithEventName:RV_EVENT_NAME];
}

/**
 * 广告隐藏回调
 *
 * @param ad 隐藏的广告对象
 */
- (void)didHideAd:(MAAd *)ad
{
    NSLog(@"rv didCloseWithAdInfo");
    [[WDAdStatusManager shareStatusManager] adCloseWithEventName:RV_EVENT_NAME];
    if (self.receiveRewardForPlacement)
    {
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:Finish adSpace:reward message:@""];
    }
    else{
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:Close adSpace:reward message:@""];
    }
    
    self.rewardedVideoDidLoadCallBackBlcok = nil;
    self.hasShowAd = NO;
    
    // Rewarded ad is hidden. Pre-load the next ad
    [self.rewardedAd loadAd];
}

/**
 * 广告展示失败回调
 *
 * @param ad 展示失败的广告对象
 * @param error 展示失败错误信息
 */
- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error
{
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:reward message:error.message];
    [self loadRV];
}

#pragma mark - MARewardedAdDelegate Protocol

/**
 * 用户获得奖励回调
 *
 * @param ad 获得奖励的广告对象
 * @param reward 用户获得的奖励信息
 */
- (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward

{
    self.receiveRewardForPlacement = YES;
    WDLog(@"didReceiveRewardForPlacement---%@-------%f",ad.description,ad.revenue);
    
    NSNumber *revenue =[NSNumber numberWithDouble:ad.revenue*1000];
    [[WDAdStatusManager shareStatusManager] adRevenue:@"RV" source:ad.networkName revenue:revenue currency:@"USD"];
    
    ADJAdRevenue *adjustAdRevenue = [[ADJAdRevenue alloc] initWithSource: ADJAdRevenueSourceAppLovinMAX];
    [adjustAdRevenue setRevenue: ad.revenue currency: @"USD"];
    [adjustAdRevenue setAdRevenueNetwork: ad.networkName];
    [adjustAdRevenue setAdRevenueUnit: ad.adUnitIdentifier];
    [adjustAdRevenue setAdRevenuePlacement: ad.placement];
        
    [Adjust trackAdRevenue: adjustAdRevenue];
}

@end
